package com.forester.foresterplatform.common.utils;

import com.forester.foresterplatform.system.entity.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

public final class SecurityUtils {

    /**
     * 获取登录的用户
     * @return
     */
    public static Optional<User> getLoginedUser() {
        return Optional.of(SecurityContextHolder.getContext())
                .map(SecurityContext::getAuthentication)
                // new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); getPrincipal 是第一个参数
                .map(Authentication::getPrincipal)
                .filter(principal -> principal instanceof User)
                .map(principal -> (User) principal);
    }

    /**
     * 获取当前登录用户的用户名
     */
    public static String getLoginUsername() {
        return getLoginedUser().map(User::getUsername).orElse(null);
    }
}
